package me.magicall.test.backup;

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import me.magicall.util.kit.Kits;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class PhoneUtil {

	public static String[] getPhoneNumInfo(final String photo) {
		final NameValuePair[] pairs = new NameValuePair[] { new NameValuePair("action", "mobile"), new NameValuePair("mobile", photo) };
		final PostMethod post = new PostMethod("http://www.ip138.com:8080/search.asp");
		post.setRequestBody(pairs);
		final HttpClient client = new HttpClient();
		client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "GBK");
		final String[] results = new String[2];
		try {
			client.executeMethod(post);
			final String result = post.getResponseBodyAsString();
			final String[] rs = result.replaceAll("&nbsp;", Kits.STR.emptyValue()).split("\r\n");
			final Pattern p1 = Pattern.compile(".*卡号归属地.*");
			final Pattern p2 = Pattern.compile(".*卡类型.*");
			for (int i = 0; i < rs.length; i++) {
				final String s = rs[i];
				final Matcher m = p1.matcher(s);
				if (m.matches()) {
					final String l = rs[i + 1];
					results[0] = l.substring(l.indexOf(">") + 1, l.lastIndexOf("<"));
				}
				m.usePattern(p2);
				if (m.matches()) {
					final String l = rs[i + 1];
					results[1] = l.substring(l.indexOf(">") + 1, l.lastIndexOf("<"));
				}
			}
		} catch (final Exception e) {
			e.printStackTrace();
		} finally {
			post.releaseConnection();
		}
		return results;
	}

	/**
	 * @param args
	 */
	public static void main(final String[] args) {
		System.out.println(Arrays.toString(getPhoneNumInfo("13333333333")));
	}

}
